package com.frame.work.lib;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.frame.work.common.util.Frame;
import com.frame.work.entity.*;
import com.frame.work.mapper.*;
import com.frame.work.mqtt.data.handle.MqttDataHandle;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

@Component
public class JointControlRespondHandle {
    @Autowired
    private TblGroupDeviceRelationMapper groupDeviceRelationMapper;

    @Autowired
    private JointControlRelationMapper jointControlRelationMapper;

    @Autowired
    private TblGatewayMapper gatewayMapper;
    @Autowired
    private TblDeviceMapper deviceMapper;

    @Autowired
    private MqttDataHandle mqttDataHandle;

    @Autowired
    private StringRedisTemplate redisTemplate;

    public void processFrame(String gatewayMac, String frameString) {

        //接收联控返回的回应信息，如果网关执行成功，则进行数据库操作
        String data =frameString;// Frame.getData(frameString);
        TblGateway tblGateway = gatewayMapper.selectOne(Wrappers.<TblGateway>lambdaQuery().eq(TblGateway::getZigbeeMac, gatewayMac));

        //获取联控绑定或解绑状态
        String state = StringUtils.substring(data, data.length() - 2, data.length() );
        String deviceMac = StringUtils.substring(data, data.length() - 24, data.length() - 8);
        String indexId = StringUtils.substring(data, data.length() - 4, data.length() - 2);

        if ("00".equals(state)){
           //如果成功状态，则根据网关mac，deviceMac，indexId查询redis，并作下一步操作
           // 例:"jointControl_"+gatewayMac + "_add_"+relation.getStartDeviceMac()+"_"+relation.getIndexId()

            String addKey = "jointControl_"+gatewayMac + "_add_"+deviceMac+"_"+indexId;
            String deleteKey = "jointControl_"+gatewayMac + "_delete_"+deviceMac+"_"+indexId;
            String addValue = "";
            String deleteValue = "";
            //redisTemplate.setKeySerializer(new JdkSerializationRedisSerializer());
            System.out.println("序列化规则"+redisTemplate.getKeySerializer());
            if (redisTemplate.opsForValue().get(addKey) != null){
                addValue = redisTemplate.opsForValue().get(addKey).toString();
            }
            if (redisTemplate.opsForValue().get(deleteKey) != null){
                deleteValue = redisTemplate.opsForValue().get(deleteKey).toString();
            }
            //String addValue = ;//(addKey);
            //String deleteValue = redisTemplate.opsForValue().get(deleteKey).toString();
            /*String addValue = jedis.get(addKey);//(addKey);
            String deleteValue = jedis.get(deleteKey);*/
            System.out.println("addValue:"+addValue);
            System.out.println("deleteValue:"+deleteValue);
        /*    int result1 = str1.indexOf("ab");
            if(result1 != -1){
                System.out.println("字符串str中包含子串“ab”"+result1);
            }else{
                System.out.println("字符串str中不包含子串“ab”"+result1);
            }*/

            if (StringUtils.isNotEmpty(addValue)){
                JSONObject jsonobject = JSONObject.parseObject(addValue);

                JointControlRelationDO jointControlRelationDO = new JointControlRelationDO();//(JointControlRelationDO)JSONObject.parseObject(addValue);
                jointControlRelationDO.setStartDeviceId(jsonobject.getString("startDeviceId"));
                jointControlRelationDO.setGateWayId(jsonobject.getString("gateWayId"));
                jointControlRelationDO.setEndDeviceId(jsonobject.getString("endDeviceId"));
                jointControlRelationDO.setStartDeviceMac(jsonobject.getString("startDeviceMac"));
                jointControlRelationDO.setEndDeviceMac(jsonobject.getString("endDeviceMac"));
                jointControlRelationDO.setIndexId(Integer.parseInt(jsonobject.getString("indexId")));
                jointControlRelationDO.setStartDeviceNum(jsonobject.getString("startDeviceNum"));
                jointControlRelationDO.setEndDeviceNum(jsonobject.getString("endDeviceNum"));
                jointControlRelationDO.setProductType(jsonobject.getString("productType"));
                jointControlRelationDO.setStartDeviceName(jsonobject.getString("startDeviceName"));
                jointControlRelationDO.setEndDeviceName(jsonobject.getString("endDeviceName"));
                //进行数据库操作并删除redis此条数据
                System.out.println(JSONObject.toJSONString(jointControlRelationDO));
                int count = jointControlRelationMapper.insert(jointControlRelationDO);
                if (count>0){
                    Boolean delete = redisTemplate.delete(addKey);
                    if (delete){
                        System.out.println("redis删除成功");
                    }
                }
                System.out.println("新增联控信息成功");
            }
            if (StringUtils.isNotEmpty(deleteValue)){
                JSONObject jsonobject = JSONObject.parseObject(deleteValue);

                JointControlRelationDO jointControlRelationDO = new JointControlRelationDO();//(JointControlRelationDO)JSONObject.parseObject(addValue);
                String id = jsonobject.getString("jointControlId");
                System.out.println("redis中的id："+id);
                //进行数据库操作并删除redis此条数据
               // System.out.println(JSONObject.toJSONString(jointControlRelationDO));
                int count = jointControlRelationMapper.deleteById(id);
                if (count>0){
                    Boolean delete = redisTemplate.delete(deleteKey);
                    if (delete){
                        System.out.println("redis删除成功");
                    }
                }
                System.out.println("删除联控信息成功");
            }
            System.out.println("联控操作成功");



        }

       /* String code = StringUtils.substring(data, data.length() - 4, data.length() - 2);
        String deviceMac = StringUtils.substring(data, 2, data.length() - 8);
        //获取网关所在的家庭
        TblGroup tblGroup = groupMapper.selectOne(Wrappers.<TblGroup>lambdaQuery()
                .eq(TblGroup::getHomeId, tblGateway.getHomeId()).eq(TblGroup::getCode, code));
        TblDevice tblDevice = deviceMapper.selectOne(Wrappers.<TblDevice>lambdaQuery().eq(TblDevice::getZigbeeMac, deviceMac));

        int update = groupDeviceRelationMapper.update(TblGroupDeviceRelation.builder().status("1").build(), Wrappers.<TblGroupDeviceRelation>lambdaQuery()
                .eq(TblGroupDeviceRelation::getGroupId, tblGroup.getId())
                .eq(TblGroupDeviceRelation::getDeviceId, tblDevice.getId()));
        mqttDataHandle.basePush(gatewayMac + "_group", deviceMac);*/
    }
}
